package mao.proxy.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author Totoro
 * @date 2020/6/10
 * @explain:
 */
public class MyJDKProxy implements InvocationHandler {
    private UserDao userDao;
    public MyJDKProxy(UserDao userDao) {
        this.userDao = userDao;
    }
    public UserDao creatProxy(){
      //  System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
        UserDao o = (UserDao) Proxy.newProxyInstance(userDao.getClass().getClassLoader(),
                userDao.getClass().getInterfaces(), this);
        return o;
    }

    @Override
    public Object invoke(Object proxy,Method method, Object[] args) throws Throwable {
        if (method.getName().equals("getName")){
            System.out.println("print by InvocationHandler");
        }
        return method.invoke(userDao,args);
    }

    public static void main(String[] args) {
        MyJDKProxy proxy = new MyJDKProxy(new UserDaoImpl());
        UserDao userDao = proxy.creatProxy();
        userDao.getName(2);
    }
}
